from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
import sys, types
import osg2 as osg

gwin_id = 0
mgr = None     # Scene manager

def display():
   global mgr
   mgr.idle()
   mgr.redraw()

def reshape(w, h):
   mgr.resize(w,h)
   glutPostRedisplay()
   
def mouse(button, state, x, y):
   print "Mouse: ", (button,state,x,y)
   if (state == GLUT_DOWN):
      mgr.mouseButtonPress(button, x, y)
   else:
      mgr.mouseButtonRelease(button, x, y)
      
   glutPostRedisplay()

def motion(x, y):
   print "Motion: ", (x,y)
   mgr.mouseMove(x,y)
   glutPostRedisplay()

def keyboard(key,x,y):
   print "Key: ", key, "  ", (x,y)
   if key == chr(27):
       osg.osgExit()
       sys.exit(0)

def initGL():
   glClearColor(0,0,0,0)
   glShadeModel(GL_FLAT)   

def setupGLUT():
   glutInit(sys.argv)
   glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH)
   #glutInitWindowSize(250, 250)
   #glutInitWindowPosition(100, 100)

   gwin_id = glutCreateWindow('pyOpenSG')

   glutReshapeFunc(reshape)
   glutDisplayFunc(display)
   glutIdleFunc(display)
   glutMouseFunc(mouse)
   glutMotionFunc(motion)
   glutKeyboardFunc(keyboard)

   return gwin_id


# ---- Main --- #
print "argv: ", sys.argv
osg.osgInit([])

win_id = setupGLUT()
#initGL()
gwin = osg.GLUTWindow.create()
gwin.setGlutId(win_id)
gwin.init()

if len(sys.argv) < 2:
   print "Loading torus...."
   scene = osg.makeTorus(0.5,2,16,16)
   osg.setName(scene, "TorusRoot")
else:
   scene = osg.SceneFileHandler.the().read(sys.argv[1])

mgr = osg.SimpleSceneManager()

mgr.setWindow(gwin)
mgr.setRoot(scene)
mgr.showAll()
mgr.setStatistics(True)
mgr.setUseTraversalAction(True)

print "------- Scene traversal ----- "
pt = osg.helpers.PrintTreeTraverser()
pt.traverse(scene)
print "----------------------------- "

glutMainLoop()




